package models

import (
	"github.com/astaxie/beego/cache"
	"github.com/astaxie/beego/orm"
	"time"
)

type DmsMenu struct {
	Id           int    `orm:"column(id);auto"`
	MenuName     string `orm:"column(menu_name);" json:"menu_name" form:"menu_name"`
	MenuHref     string `orm:"column(menu_href);" json:"menu_href" form:"menu_href"`
	ParentMenuId string `orm:"column(parent_menu_id);" json:"parent_menu_id" form:"parent_menu_id"`
	MenuNo       string `orm:"column(menu_no);" json:"menu_no" form:"menu_no"`
	MenuId       string `orm:"column(menu_id);" json:"menu_id" form:"menu_id"`
}

var menucache, _ = cache.NewCache("memory", `{"interval":600}`)
var menucachePrefix = "menu_"

const menuCachTime = 600 * time.Second

func (u *DmsMenu) TableName() string {
	return "dms_menu"
}

func init() {
	orm.RegisterModel(new(DmsMenu))
}
func GetMenu() (data []*DmsMenu, err error) {
	key := menucachePrefix + "allmenus"
	if menucache.IsExist(key) {
		menus := menucache.Get(key)
		data = menus.([]*DmsMenu)
		err = nil
	} else {
		o := orm.NewOrm()
		_, err = o.Raw("SELECT * FROM dms_menu where parent_menu_id = 1 order by menu_no asc").QueryRows(&data)
		if err == nil{
			menucache.Put(key, data, menuCachTime)
		}
	}
	return
}

func GetMenuByMenuId(dataType string) (data *DmsMenu, err error) {
	key := menucachePrefix + dataType
	if menucache.IsExist(key) {
		menus := menucache.Get(key)
		data = menus.(*DmsMenu)
		err = nil
	} else {
		o := orm.NewOrm()
		err = o.Raw("SELECT * FROM dms_menu where  menu_id = ?",dataType).QueryRow(&data)
		if err == nil{
			menucache.Put(key, data, menuCachTime)
		}
	}
	return
}